<script setup>
import { reactive, onMounted, onBeforeUnmount } from 'vue'
import MediaGrid from './components/MediaGrid.vue'
import FolderPanel from './components/FolderPanel.vue'
import { ElMessage } from 'element-plus'

// 状态管理
const state = reactive({
  sourceFolder: '',
  targetFolder: '',
  selectedTargetPath: '',
  selectedFiles: new Set(),
  loading: false,
  filesMoved: false
})

// 获取文件夹名称
const getFolderName = (folderPath) => {
  return folderPath ? folderPath.split(/[/\\]/).pop() : '目标文件夹'
}

// 保存路径状态
const savePaths = async () => {
  try {
    await window.mediaManager.savePaths({
      sourceFolder: state.sourceFolder,
      targetFolder: state.targetFolder
    })
  } catch (error) {
    console.error('Save paths failed:', error)
  }
}

// 加载保存的路径
const loadSavedPaths = async () => {
  try {
    const paths = await window.mediaManager.getSavedPaths()
    if (paths.sourceFolder) {
      state.sourceFolder = paths.sourceFolder
    }
    if (paths.targetFolder) {
      state.targetFolder = paths.targetFolder
      state.selectedTargetPath = paths.targetFolder
    }
  } catch (error) {
    console.error('Load saved paths failed:', error)
  }
}

// 处理源文件夹选择
const handleSourceSelect = async () => {
  try {
    const folder = await window.mediaManager.selectFolder()
    if (folder) {
      state.sourceFolder = folder
      state.selectedFiles.clear()
      savePaths()
    }
  } catch (error) {
    console.error('Select source folder failed:', error)
    ElMessage.error('选择文件夹失败')
  }
}

// 处理目标文件夹选择
const handleTargetSelect = async () => {
  try {
    const folder = await window.mediaManager.selectFolder()
    if (folder) {
      state.targetFolder = folder
      state.selectedTargetPath = folder
      savePaths()
    }
  } catch (error) {
    console.error('Select target folder failed:', error)
    ElMessage.error('选择文件夹失败')
  }
}

// 处理子文件夹选择
const handleTargetPathSelect = (path) => {
  state.selectedTargetPath = path
}

// 处理文件选择更新
const handleSelectionChange = (selectedPaths) => {
  state.filesMoved = false // 重置移动状态
  state.selectedFiles = new Set(selectedPaths)
}

// 处理文件移动
const handleMoveFiles = async () => {
  if (!state.selectedTargetPath || state.selectedFiles.size === 0 || state.loading) return

  state.loading = true
  state.filesMoved = false // 确保初始状态为 false
  
  try {
    const filesToMove = Array.from(state.selectedFiles)
    await window.mediaManager.moveFiles(filesToMove, state.selectedTargetPath)
    
    // 设置移动成功状态
    state.filesMoved = true
    
    ElMessage.success('文件移动成功')
  } catch (error) {
    console.error('Move files failed:', error)
    ElMessage.error('文件移动失败')
  } finally {
    state.loading = false
    // 延迟重置移动状态
    setTimeout(() => {
      state.filesMoved = false
    }, 100)
  }
}

// 添加键盘事件处理函数
const handleKeyPress = (event) => {
  // 检查是否按下 Enter 键
  if (event.key === 'Enter') {
    // 检查是否满足移动条件
    if (state.selectedTargetPath && state.selectedFiles.size > 0 && !state.loading) {
      handleMoveFiles()
    }
  }
}

// 组件挂载时添加事件监听
onMounted(() => {
  loadSavedPaths()
  // 添加键盘事件监听
  window.addEventListener('keydown', handleKeyPress)
})

// 组件卸载前移除事件监听
onBeforeUnmount(() => {
  window.removeEventListener('keydown', handleKeyPress)
})
</script>

<template>
  <div class="app-container">
    <div class="main-panel">
      <div class="panel-header">
        <h2>媒体文件</h2>
        <div class="header-actions">
          <el-button @click="handleSourceSelect">选择文件夹</el-button>
          <el-button 
            type="primary" 
            :loading="state.loading"
            :disabled="!state.selectedTargetPath || state.selectedFiles.size === 0"
            @click="handleMoveFiles"
          >
            移动到 {{ getFolderName(state.selectedTargetPath) }}
          </el-button>
        </div>
      </div>
      
      <div class="source-path" v-if="state.sourceFolder">
        当前文件夹: {{ state.sourceFolder }}
      </div>

      <MediaGrid
        :folder-path="state.sourceFolder"
        :selected-files="Array.from(state.selectedFiles)"
        :moved-files="state.filesMoved"
        :target-folder="state.targetFolder"
        :selected-target-path="state.selectedTargetPath"
        @selection-change="handleSelectionChange"
        @target-select="handleTargetSelect"
        @target-path-select="handleTargetPathSelect"
        @move-files="handleMoveFiles"
      />
    </div>
    <div class="folder-panel">
      <FolderPanel
      :folder="state.targetFolder"
      :selected-path="state.selectedTargetPath"
      @select="handleTargetSelect"
      @path-select="handleTargetPathSelect"
      />
    </div>
  </div>
</template>

<style scoped>
.app-container {
  display: flex;
  height: 97vh;
  padding: 20px;
  gap: 20px;
  background: #f5f7fa;
  box-sizing: border-box;
  overflow: hidden;
}

.main-panel {
  flex: 4;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
  min-height: 0;
}

.panel-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

.panel-header h2 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.source-path {
  padding: 10px 20px;
  background: #f5f7fa;
  color: #606266;
  font-size: 14px;
  flex-shrink: 0;
}

.folder-panel {
  flex: 1;
  height: 93vh;
}

</style>
